package com.mengchengnet.chaperonage.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.mengchengnet.chaperonage.BaseActivity;
import com.mengchengnet.chaperonage.R;
import com.mengchengnet.chaperonage.util.PreferenceUtil;
import com.mengchengnet.chaperonage.util.Url;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/8/7.
 * 登录页
 */

public class LoginActivity extends BaseActivity implements OnClickListener{
    private TextView tv_register,tv_forget,login_care;
    private Button login;
    private RequestQueue requestQueue;
    private EditText ed_phone,ed_password;
    private TextInputLayout username,password;
    private static final String TAG = "LoginActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
    }

    private void initView() {
        toolbarState =TOOLBAR_STYLE_BACK_TITLE;
        initToolbar("用户登录");
        tv_register= (TextView) findViewById(R.id.login_tv_goRegister);
        tv_forget= (TextView) findViewById(R.id.login_tv_goForgetPass);
        login= (Button) findViewById(R.id.login_btn_login);
        tv_register.setOnClickListener(this);
        tv_forget.setOnClickListener(this);
        login.setOnClickListener(this);
        requestQueue= Volley.newRequestQueue(getApplication());

        ed_phone= (EditText) findViewById(R.id.login_ed_phone);
        ed_password= (EditText) findViewById(R.id.login_ed_password);

        username= (TextInputLayout) findViewById(R.id.usernameWrapper);
        password= (TextInputLayout) findViewById(R.id.passwordWrapper);
        username.setHint("用户名(手机号)");
        password.setHint("密码");

        login_care= (TextView) findViewById(R.id.login_tv_goRegister2);
        login_care.setOnClickListener(this);

    }


    private void login() {
        StringRequest request = new StringRequest(Request.Method.POST, Url.Login,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        Log.e("登录界面", "登录接口返回值："+result );
                        JSONObject jsonObject;
                        try {
                            jsonObject = new JSONObject(result);
                            if (jsonObject.getString("code").equals("00")){
                                PreferenceUtil.putString(getApplicationContext(),"phone",ed_phone.getText().toString());
                                PreferenceUtil.putString(getApplicationContext(),"userId",jsonObject.getString("userId"));
                                PreferenceUtil.putString(getApplicationContext(),"userType","0");
                                PreferenceUtil.putString(getApplicationContext(),"avatar",jsonObject.getString("avatar"));
                                PreferenceUtil.putString(getApplicationContext(),"userName",jsonObject.getString("username"));
                                Log.e(TAG, "用户头像: "+jsonObject.getString("avatar"));
                                Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                                PreferenceUtil.putBoolean(getApplication(),"isLogin",true);
                                startActivityAndFinish(MainActivity.class);

                            }
                            else if(jsonObject.getString("code").equals("01")){
                                Toast.makeText(LoginActivity.this, "密码错误", Toast.LENGTH_SHORT).show();
                                return;
                            }else{
                                Toast.makeText(LoginActivity.this, "登陆失败", Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError arg0) {
                Log.e("error", "error: "+arg0.getMessage() );
                Toast.makeText(LoginActivity.this, "网络异常请稍后重试！", Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("version", PreferenceUtil.getString(getApplication(),"versionCode"));
                map.put("loginId", ed_phone.getText().toString());
                map.put("password", ed_password.getText().toString().trim());
                map.put("type", "0");
                return map;
            }
        };
        request.setTag("GetFenZu");
        request.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, // 默认超时时间，应设置一个稍微大点儿的
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, // 默认最大尝试次数
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        requestQueue.add(request);

    }

    @Override
    protected void onResume() {
        super.onResume();
        ed_password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length()>5){
                    login.setClickable(true);
                }

            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.login_tv_goRegister:
                Intent intent=new Intent();
                intent.setClass(LoginActivity.this,RegisteredActivity.class);
                startActivity(intent);
                break;
            case R.id.login_tv_goForgetPass:
                Intent intent2=new Intent();
                intent2.setClass(LoginActivity.this,FindPassWord.class);
                startActivity(intent2);
                //startActivityAndFinish(FindPassWord.class);
                break;
            case R.id.login_btn_login:
                if (ed_phone.length()<11){
                    ed_phone.setError("手机号格式错误");
                }else if(ed_password.length()<6) {
                    ed_password.setError("密码长度太短");
                }else {
                    login();
                }

                break;
            case R.id.login_tv_goRegister2:
                Intent intentCare =new Intent(LoginActivity.this,NurseLoginActivity.class);
                startActivity(intentCare);
                finish();
                break;

        }
    }
}
